package com.klhappy.houyuan.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import com.google.gson.Gson;
import com.klhappy.houyuan.R;
import com.klhappy.houyuan.adapter.AllBaseAdapter;
import com.klhappy.houyuan.bean.AddressBean.DeAddressBean;
import com.klhappy.houyuan.bean.AddressBean.DefaultAddress;
import com.klhappy.houyuan.bean.BaseJsonBean;
import com.klhappy.houyuan.bean.ConfirmBean;
import com.klhappy.houyuan.bean.DingDanBean.ChargeBean;
import com.klhappy.houyuan.bean.DingDanBean.PayOrderBean;
import com.klhappy.houyuan.bean.GoodsAllBean;
import com.klhappy.houyuan.bean.HouYuanBean.AmountFreeBean;
import com.klhappy.houyuan.bean.XiangqingBean.DialteBean;
import com.klhappy.houyuan.constant.KeyConstant;
import com.klhappy.houyuan.constant.UrlConstant;
import com.klhappy.houyuan.interfaces.CallBackInterModle;
import com.klhappy.houyuan.modle.HouYuanModle;
import com.klhappy.houyuan.utils.JsonCode;
import com.klhappy.houyuan.view.AbsActivity;
import com.klhappy.houyuan.view.UnfoldedListView;
import com.pingplusplus.android.PaymentActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ConfirmOrderActivity extends AbsActivity implements CallBackInterModle {
    @InjectView(R.id.lv_goods)
    UnfoldedListView lvGoods;
    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.tv_timeDes)
    TextView tv_timeDes;
    @InjectView(R.id.tv_time)
    TextView tv_time;
    @InjectView(R.id.pay_tv)
    TextView pay_tv;
    @InjectView(R.id.tv_sum)
    TextView tv_sum;
    @InjectView(R.id.tv_address)
    TextView tv_address;
    @InjectView(R.id.tv_price)
    TextView tv_price;
    @InjectView(R.id.tv_leaveMessage)
    EditText tv_leaveMessage;
    @InjectView(R.id.tv_stamp)
    TextView tv_stamp;
    @InjectView(R.id.add_loction)
    RelativeLayout add_loction;
    @InjectView(R.id.ll_add_loction)
    LinearLayout ll_add_loction;

    @OnClick(R.id.click_ra)
    public void click_ra() {
        finish();
    }

    @OnClick(R.id.add_loction)
    public void add_loction() {
        Intent intent = new Intent(this, Add_AddressActivity.class);
        startActivityForResult(intent, 50);
    }

    @OnClick(R.id.ll_add_loction)
    public void ll_add_loction() {
        Intent intent = new Intent(this, AddLocationActivity.class);
        startActivityForResult(intent, 40);
    }

    @OnClick(R.id.ll_stamp)
    public void ll_stamp() {
        Intent intent = new Intent(this, AbleStampActivity.class);
        startActivityForResult(intent, 30);
    }

    @OnClick(R.id.pay_tv)
    public void pay_tv() {
        Intent intent = new Intent(this, PayTypesActivity.class);
        startActivityForResult(intent, 20);
    }

    @OnClick(R.id.time_rl)
    public void time_rl() {
        Intent intent = new Intent(this, DeliverTimeActivity.class);
        startActivityForResult(intent, 10);
    }

    @OnClick(R.id.btn_confirm)
    public void btn_confirm() {
        if (isStatus) {
            showDialog("支付中...");
            setJson();
        } else {
            showToastx("您的订单里有库存不足的商品!");
        }
    }

    private static final int REQUEST_CODE_PAYMENT = 1;
    private TextView tv_num;
    private TextView tv_amount;
    private TextView tv_xia_time;
    private List<GoodsAllBean> itemList;
    private HouYuanModle modle;
    private ConfirmBean confirmBean;
    private AmountFreeBean freeBean;
    private PayOrderBean orderBean;
    private ChargeBean chargeBean;
    private String day;
    private String id;
    private String stamp_id;
    private String datas;
    private String channel;
    private DeAddressBean address;
    private DefaultAddress deaddress;
    private List<DialteBean> dialteBeanList;
    private boolean isStatus = true;//判断库存

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.confirm_order);
        ButterKnife.inject(this);
        title.setText("确认订单");
        modle = new HouYuanModle(this);
        modle.setCallBackInterModle(this);
        intView();
    }

    private void intView() {
        View headerView = LayoutInflater.from(this).inflate(R.layout.confirm_order_list_header, null);
        View footerView = LayoutInflater.from(this).inflate(R.layout.confirm_order_list_footer, null);
        lvGoods.addHeaderView(headerView);
        lvGoods.addFooterView(footerView);

        tv_num = (TextView) footerView.findViewById(R.id.tv_num);
        tv_amount = (TextView) footerView.findViewById(R.id.tv_amount);
        tv_xia_time = (TextView) headerView.findViewById(R.id.tv_xia_time);
        setView();
    }

    private void setView() {
        itemList = (ArrayList) this.getIntent().getSerializableExtra("goods");
        tv_num.setText("共" + itemList.size() + "样商品");
        float money = 0;
        String all_id = null;
        for (int i = 0; i < itemList.size(); i++) {
            money = money + Integer.parseInt(itemList.get(i).getCount()) * Float.parseFloat(itemList.get(i).getPrice());
            if (i == 0) {
                all_id = itemList.get(i).getId() + ",";
            } else if (i < (itemList.size() - 1) && i > 0) {
                all_id = all_id + itemList.get(i).getId() + ",";
            } else {
                all_id = all_id + itemList.get(i).getId();
            }
        }

        day = mConfigManage.get(KeyConstant.DAY, "");
        String timex = mConfigManage.get(KeyConstant.TIME, "");
        datas = mConfigManage.get(KeyConstant.DATA, "");
        if (!TextUtils.isEmpty(day) && !TextUtils.isEmpty(timex) && !TextUtils.isEmpty(datas)){
            tv_timeDes.setText(day + "  " + timex);
            tv_time.setText(datas + "  之前");
        }
        tv_amount.setText("合计 : " + money + "元");
        tv_sum.setText(money + "元");
        String time = itemList.get(0).getTime();
        if ("".equals(time)) {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String date = sDateFormat.format(new java.util.Date());
            Calendar c = Calendar.getInstance();
            c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
            if ("1".equals(mWay)) {
                mWay = "周日";
            } else if ("2".equals(mWay)) {
                mWay = "周一";
            } else if ("3".equals(mWay)) {
                mWay = "周二";
            } else if ("4".equals(mWay)) {
                mWay = "周三";
            } else if ("5".equals(mWay)) {
                mWay = "周四";
            } else if ("6".equals(mWay)) {
                mWay = "周五";
            } else if ("7".equals(mWay)) {
                mWay = "周六";
            }
            tv_xia_time.setText(date + mWay);
        } else {
            tv_xia_time.setText(time);
        }
        if (null != mConfigManage.get(KeyConstant.PAY, "") && !"".equals(mConfigManage.get(KeyConstant.PAY, ""))){
            pay_tv.setText(mConfigManage.get(KeyConstant.PAY, ""));
        }else {
            pay_tv.setText("支付宝");
        }

        lvGoods.setAdapter(new AllBaseAdapter(ConfirmOrderActivity.this, itemList));

        modle.getFee(money + "");
        modle.getDeAddress();
        modle.setTock(all_id);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10:
                try {
                    day = data.getStringExtra("day");
                    String time = data.getStringExtra("time");
                    datas = data.getStringExtra("data");
                    tv_timeDes.setText(day + "  " + time);
                    tv_time.setText(datas + "  之前");
                } catch (Exception e) {
                    Log.e("this", e.toString());
                }
                break;
            case 20:
                try {
                    String pay = data.getStringExtra("pay");
                    pay_tv.setText(pay);
                } catch (Exception e) {
                    Log.e("this", e.toString());
                }
                break;
            case 30:
                try {
                    String stamp = data.getStringExtra("stamp");
                    stamp_id = data.getStringExtra("stamp_id");
                    if (stamp == null) {
                        tv_stamp.setText("无粮票");
                    } else {
                        tv_stamp.setText("￥ " + stamp);
                    }
                } catch (Exception e) {
                    Log.e("this", e.toString());
                }

                break;
            case 40:
                try {
                    String address = data.getStringExtra("address");
                    if (address != null) {
                        ll_add_loction.setVisibility(View.GONE);
                        add_loction.setVisibility(View.VISIBLE);
                        tv_address.setText(address);
                    } else {
                        ll_add_loction.setVisibility(View.VISIBLE);
                        add_loction.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    Log.e("this", e.toString());
                }
                break;
            case 50:
                try {
                    String addressx = data.getStringExtra("addressx");
                    id = data.getStringExtra("id");
                    if (addressx != null) {
                        ll_add_loction.setVisibility(View.GONE);
                        add_loction.setVisibility(View.VISIBLE);
                        tv_address.setText(addressx);
                    } else {
                        ll_add_loction.setVisibility(View.VISIBLE);
                        add_loction.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    Log.e("this", e.toString());
                }

                break;
            default:
                break;
        }
    }

    @Override
    public void CallBackFromModle(String url, BaseJsonBean o) {
        if (url.equals(UrlConstant.STOCK_URL)) {
            if (o.getCode() == 200) {
                Gson gson = new Gson();
                Log.e("this", gson.toJson(o));
                dialteBeanList = JsonCode.getClassList(o.getEntity(), DialteBean.class);
                for (int i = 0; i < dialteBeanList.size(); i++) {
                    if (dialteBeanList.get(i).g_status.equals("10")) {
                        isStatus = false;
                    }
                }
            }
        } else if (url.equals(UrlConstant.FEE_URL)) {
            if (o.getCode() == 200) {
                freeBean = JsonCode.getClass(o.getEntity(), AmountFreeBean.class);
                tv_price.setText("￥ " + freeBean.getOr_amount_fee());
            }
        } else if (url.equals(UrlConstant.BUIL_ORDER_URL)) {
            if (o.getCode() == 200) {
                orderBean = JsonCode.getClass(o.getEntity(), PayOrderBean.class);
                modle.getCancel(orderBean.getId() + "", channel);
            } else {
                showToast(o.getMsg());
            }
        } else if (url.equals(UrlConstant.TOPAY_URL)) {
            if (o.getCode() == 200) {
                Gson gson = new Gson();
                chargeBean = JsonCode.getClass(o.getEntity(), ChargeBean.class);
                String json = gson.toJson(chargeBean.getCharge());
                pay(json);
            }
            closeDialog();
        } else if (url.equals(UrlConstant.DEADDRESS_URL)) {
            if (o.getCode() == 200) {
                address = JsonCode.getClass(o.getEntity(), DeAddressBean.class);
                deaddress = JsonCode.getClass(address.getDefaultAddress(), DefaultAddress.class);
                if (deaddress != null) {
                    ll_add_loction.setVisibility(View.GONE);
                    add_loction.setVisibility(View.VISIBLE);
                    tv_address.setText(deaddress.getAddress());
                } else {
                    ll_add_loction.setVisibility(View.VISIBLE);
                    add_loction.setVisibility(View.GONE);
                }
            }
        }
    }

    /**
     * @Nobject 商品的json数据集合
     */
    private void setJson() {
        confirmBean = new ConfirmBean();
        JSONObject Nobject = new JSONObject();
        JSONArray array = new JSONArray();
        try {
            for (int i = 0; i < itemList.size(); i++) {
                JSONObject object = new JSONObject();
                object.put("id", itemList.get(i).getId() + "");
                object.put("no", itemList.get(i).getCount());
                array.put(object);
            }
            Nobject.put("goods", array);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String adress = deaddress.getId() + "";

        String time = day + " " + datas;
        String count = tv_leaveMessage.getText().toString();
        if (pay_tv.getText().toString().equals("支付宝")) {
            channel = "alipay";
        } else if (pay_tv.getText().toString().equals("微信")) {
            channel = "wx";
        } else if (pay_tv.getText().toString().equals("货到付款")){
            channel = "daofu";
        }else {
            channel = "";
        }

        if (day == null) {
            showToastx("请选择派送时间!");
            closeDialog();
        } else if ("".equals(adress) && "".equals(id)) {
            showToastx("请选择收货地址!");
            closeDialog();
        } else if ("".equals(channel)) {
            showToastx("请选择支付方式!");
            closeDialog();
        } else {
            confirmBean.setConfirmBean(Nobject, stamp_id, id, adress, time, count, channel);
            if (confirmBean != null) {
                modle.setConfirm(confirmBean);
            }
        }
    }

    private void pay(String charge) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        ComponentName componentName = new ComponentName(packageName, packageName + ".wxapi.WXPayEntryActivity");
        intent.setComponent(componentName);
        intent.putExtra(PaymentActivity.EXTRA_CHARGE, charge);
        startActivityForResult(intent, REQUEST_CODE_PAYMENT);
    }
}
